﻿using Coomtools.commclass;
using Sunny.UI;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Coomtools.weightclasses;
using System.IO;

namespace CYLScheck.UIcomm
{

    public partial class WegihtFrm :UIForm
    {
        //public List<Myweightbase.UIPLU> weightPLUlist;
       public BindingList<Uipluitem> UIplulist = new BindingList<Uipluitem>();

        /// <summary>
        /// 包含所有可以操作电子称的 字段类型   对应  key 可操作的电子称名称 value 设计好的电子称类
        /// </summary>
        Dictionary<string, string> Getweights = new Dictionary<string, string>();

        string plufilePath = "";
 

        public WegihtFrm()
        {
            InitializeComponent();
        }

        /// <summary>
        /// 通过反射得到所支持的电子型号
        /// </summary>
        void GetAssemblyweightclasses()
        {
            Assembly Getweightsasm;

            try
            {        ///反射 dll程序集
                Getweightsasm = Assembly.LoadFrom("Coomtools.dll");
                //反射  改程序集中对应的  电子称信息汇聚类
                Type WeightType = Getweightsasm.GetType("Coomtools.weightclasses.Myweightclasses");
                // 反射  实例化该  电子信息汇聚类
                object MyWeights = Activator.CreateInstance(WeightType);
                // 对 字典类型的   获得到的电子称集合赋值
                Getweights = (Dictionary<string, string>)WeightType.GetField("Allweights").GetValue(MyWeights);
                if (Getweights.Count > 0)
                {
                    ComBox_weightclasses.Items.Clear();
                    foreach (var key in Getweights.Keys)
                    {
                        ComBox_weightclasses.Items.Add(key);
                    }
                    ///?????????目前选得到的第一项  后期加入 ini文件中或者序列化的类中 记忆上次用户的选择？？？？？？？？
                    ComBox_weightclasses.SelectedIndex = 0;
                }



            }
            catch (Exception ex)
            {

                throw ex;
            }

        }

       /// <summary>
       /// 反射调用确定 对应的类 读取PLU文件 和实现
       /// </summary>
        void ReadPLUFile_UseNeedWeightclass()
        {
            Assembly Getweightsasm;

            try
            {
                ///反射 dll程序集
                //string path = "D:\gitee\CYLScheck\bin\Debug \"+ "Coomtools.dll";
                //string path = @"D:\gitee\CYLScheck\bin\Debug\Coomtools.dll";
                //Getweightsasm = Assembly.Load(path);
                Getweightsasm = Assembly.LoadFrom("Coomtools.dll");
                //反射  改程序集中对应的  所需要的电子称类
                string UseClassName = Getweights.GetValue(ComBox_weightclasses.Text.Trim());
                    
                Type WeightType = Getweightsasm.GetType("Coomtools.weightclasses." + UseClassName);
                // 反射  实例化该  电子称类，必须为 无参数 的构造方法
                object UseWeight = Activator.CreateInstance(WeightType);

          
                //***************具体操作类方法获取********
               
                
                MethodInfo minfo = WeightType.GetMethod("CheckIsNeedFile");
               bool IsMyNeedFile=  (bool) minfo.Invoke(UseWeight, new object[] { plufilePath });
               
                //检测到是本类能处理的文件 再往下继续执行
                if (IsMyNeedFile)
                {
                    //MessageBox.Show("是能处理的文件准备往下执行");
                   
                    MethodInfo minfo2 = WeightType.GetMethod("ReadPLuResourseFile");

     
                 var d=  minfo2.Invoke(UseWeight, new object[] { plufilePath });
                    //应用 weightbase 基类里的数据类型 Myweightbase.PLU 不然 强制转换报错 
                     UIplulist.Clear();
                    UIplulist = d as BindingList<Uipluitem> ;
                   //重置电子称标识为 自定义在标识 如果输入在不对改为默认在99
                    if (IsTwoInteger(Txbox_WeightFlage.Text.Trim()))
                    {
                            foreach (var UIpluitem in UIplulist)
                            {
                                 UIpluitem.WeightFlage = Txbox_WeightFlage.Text.Trim();
                              }

                    }
                    else
                    {
                        UIMessageBox.ShowError("电子秤标识不是有效在两位整数，将改为默认标识 99");
                        foreach (var UIpluitem in UIplulist)
                        {
                            UIpluitem.WeightFlage = "99";
                        }

                    }
                 
                      //界面控件绑定数据源
                    uiDataGridView1.DataSource = UIplulist;

                }

            }
            catch (Exception e)
            {

               UIMessageBox.Show("本文件解析异常！"+ e.Message);
                //throw;
            }


        }

        public  bool IsTwoInteger(string s)
        {
            string pattern = @"^\d*$";
            if ( System.Text.RegularExpressions.Regex.IsMatch(s, pattern))
            {
                if (Convert.ToInt32(s) >0 &&  Convert.ToInt32(s)<100)
                {
                    return true;
                }
            }
        return false;
        }
        private void WegihtFrm_Load(object sender, EventArgs e)
     {
               
            
            this.Style = Gobleset.Gobel_userstyle;
            //不绑定不需要的列
            uiDataGridView1.AutoGenerateColumns = false;

            ////不能自动增加行
            uiDataGridView1.AllowUserToAddRows = false;

            //不能多选
            uiDataGridView1.MultiSelect = false;
            //选择整行
            uiDataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
            // 行前不显示三角
            uiDataGridView1.RowHeadersVisible = false;
       
            //***************通过反射得到所支持的电子型号*******************************

            GetAssemblyweightclasses();



        }

        private void WegihtFrm_FormClosing(object sender, FormClosingEventArgs e)
        {
            //Getweightsasm = null;
            //Getweights.Clear();
            //Getweights = null;
        }

        private void Button_OpenPluPath_Click(object sender, EventArgs e)
        {
          
                   
            UIplulist.Clear();
            uiDataGridView1.DataSource = UIplulist;
           
                  OpenFileDialog openpludlg=new OpenFileDialog();
            // 打开文件初始目录为本程序所在目录
         
            openpludlg.InitialDirectory =Application.StartupPath; 
            //限定文件打开类型
            openpludlg.Filter = "电子称导出文件(*.txt,*.txp）|*.txt;*.txp";
            
           
            if (openpludlg.ShowDialog()==DialogResult.OK)
            {
                plufilePath = openpludlg.FileName;
     
                ///实例化需要的电子称类
                ReadPLUFile_UseNeedWeightclass();



            }

          

        }

        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {

        }
        /// <summary>
        /// 对要传输的plu列表进行检查
        /// </summary>
       bool PLUListCheck(BindingList<Uipluitem> uipluList)
        {
            foreach (var Plu in uipluList)
            {

                if (Plu.PLUcode!=Plu.lfcode)
                {
                    Plu.lfcode = Plu.PLUcode;
                }


            }

             return true;
        }
        private void bt_sendEweight_Click(object sender, EventArgs e)
        {
            //这里应该添加对 uiplulist 里面的数据进行检查
            if (PLUListCheck(UIplulist))
            {
              TranfEweightFrm tranfEweihtFrm = new  TranfEweightFrm(UIplulist);
            tranfEweihtFrm.ShowDialog();
            }
            else
            {
                UIMessageDialog.ShowWarningDialog(this,"要传输的信息有错误！"+UIStyle.Orange);
            }
          
        }

        private void panel1_Paint(object sender, PaintEventArgs e)
        {

        }

        private void ButtonAdd_Click(object sender, EventArgs e)
        {
            Uipluitem newplu = new Uipluitem();
            
            if (UIplulist.Count>0)
            {
                newplu.WeightFlage = UIplulist[UIplulist.Count - 1].WeightFlage;
                newplu.barcodeclass = UIplulist[UIplulist.Count - 1].barcodeclass;
                newplu.barcodeclassCode= UIplulist[UIplulist.Count - 1].barcodeclassCode;
              newplu.unit= UIplulist[UIplulist.Count - 1].unit; 
                newplu.unitcode= UIplulist[UIplulist.Count - 1].unitcode;
                newplu.serialnumber = Convert.ToString(UIplulist.Count + 1);

                  UIplulist.Add(newplu);
            }
            else
            {
                
          newplu.serialnumber =Convert.ToString(UIplulist.Count + 1) ;
            newplu.WeightFlage = Txbox_WeightFlage.Text.Trim();
        
                UIplulist.Add(newplu);
            uiDataGridView1.DataSource = UIplulist;
            }
           
      
        }

        private void ButtonDelete_Click(object sender, EventArgs e)
        {
            if (uiDataGridView1.Rows.Count>0)
            {
                UIplulist.RemoveAt(uiDataGridView1.SelectedIndex);
               

            }
        }
    }






}
